package com.agriculture.controller;

import com.agriculture.dto.DevicePathDto;
import com.agriculture.entity.DevicePositionHistory;
import com.agriculture.entity.GeoDevicePath;
import com.agriculture.service.GeoDevicePathService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityNotFoundException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/paths")
@CrossOrigin(origins = "*")
public class GeoDevicePathController {
    
    @Autowired
    private GeoDevicePathService pathService;
    
    @GetMapping
    public List<DevicePathDto> getAllPaths() {
        return pathService.getAllPaths().stream()
                .map(pathService::convertToDto)
                .collect(Collectors.toList());
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<DevicePathDto> getPathById(@PathVariable Integer id) {
        Optional<GeoDevicePath> path = pathService.getPathById(id);
        if (path.isPresent()) {
            return ResponseEntity.ok(pathService.convertToDto(path.get()));
        } else {
            throw new EntityNotFoundException("路径不存在");
        }
    }
    
    @GetMapping("/device/{deviceId}")
    public List<DevicePathDto> getPathsByDeviceId(@PathVariable Integer deviceId) {
        return pathService.getPathsByDeviceId(deviceId).stream()
                .map(pathService::convertToDto)
                .collect(Collectors.toList());
    }
    
    @GetMapping("/device/{deviceId}/time-range")
    public List<DevicePathDto> getPathsByDeviceAndTimeRange(
            @PathVariable Integer deviceId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime) {
        
        System.out.println("收到历史轨迹请求 - 设备ID: " + deviceId + ", 开始时间: " + startTime + ", 结束时间: " + endTime);
        
        // 使用专门的历史轨迹方法
        List<DevicePathDto> historyPaths = pathService.getHistoryPathsByDeviceAndTimeRange(deviceId, startTime, endTime);
        
        System.out.println("返回历史轨迹数量: " + historyPaths.size());
        
        return historyPaths;
    }
    
    @PostMapping
    public ResponseEntity<DevicePathDto> createPath(@RequestBody DevicePathDto pathDto) {
        GeoDevicePath path = pathService.createPathFromPoints(
            pathDto.getDeviceId(), pathDto.getPathPoints(), pathDto.getPathName(),
            pathDto.getStartTime(), pathDto.getEndTime()
        );
        return ResponseEntity.status(HttpStatus.CREATED).body(pathService.convertToDto(path));
    }
    
    /**
     * 调试接口 - 获取原始历史位置数据
     */
    @GetMapping("/device/{deviceId}/history-debug")
    public ResponseEntity<List<Map<String, Object>>> getHistoryPositionsDebug(
            @PathVariable Integer deviceId,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime) {
        
        System.out.println("调试接口 - 设备ID: " + deviceId + ", 开始时间: " + startTime + ", 结束时间: " + endTime);
        
        List<DevicePositionHistory> positions;
        if (startTime != null && endTime != null) {
            positions = pathService.getHistoryPositions(deviceId, startTime, endTime);
        } else {
            positions = pathService.getHistoryPositions(deviceId, null, null);
        }
        
        List<Map<String, Object>> result = new ArrayList<>();
        for (DevicePositionHistory pos : positions) {
            Map<String, Object> item = new HashMap<>();
            item.put("id", pos.getId());
            item.put("deviceId", pos.getDeviceId());
            item.put("longitude", pos.getPosition().getX());
            item.put("latitude", pos.getPosition().getY());
            item.put("recordedTime", pos.getRecordedTime());
            result.add(item);
        }
        
        System.out.println("找到历史位置数据: " + result.size() + " 条");
        
        return ResponseEntity.ok(result);
    }
}